package corpus;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;


public class WordPolarityCorpus {
	private Map<String, Map<String, WordPolarity>> posWordPol;
	private BufferedReader br;

	public WordPolarityCorpus(File db) throws IOException {
		br = new BufferedReader(new FileReader(db));
		posWordPol = new HashMap<String, Map<String, WordPolarity>>();

		while (true) {
			String line = br.readLine();
			if (line == null)
				break;
			Scanner scr = new Scanner(line);
			scr.useDelimiter("\\s+|=");

			Word word = new Word();
			WordPolarity pol = new WordPolarity();
			while (scr.hasNext()) {
				String key = scr.next();
				String value = scr.next();
				if (key.equals("word1")) {
					word.setWord(value);
				} else if (key.equals("type")) {
					if (value.equals("strongsubj"))
						pol.setStrong(true);
					else
						pol.setStrong(false);
				} else if (key.equals("pos1")) {
					word.setPos(translatePTB(value));
				} else if (key.equals("stemmed1")) {
					if (key.equals("y"))
						pol.setStemmed(true);
					else
						pol.setStemmed(false);
				} else if (key.equals("priorpolarity")) {
					if (value.matches("negative|neutral|both|weak(neg|pos)"))
						pol.setPriorpolarity(false);
					else
						pol.setPriorpolarity(true);
				} else if (key.equals("emotion"))
					pol.setEmotion(value);
			}
			Map<String, WordPolarity> words;
			if (posWordPol.containsKey(word.getPos()))
				words = posWordPol.get(word.getPos());
			else {
				words = new HashMap<String, WordPolarity>();
				posWordPol.put(word.getPos(), words);
			}
			words.put(word.getWord(), pol);
		}
	}

	// adverb RB,RBR,RBS
	// verb VB,VBD,VBG,VBN,VBP,VBZ
	// noun NN,NNP,NNPS,NNS
	// adj JJ,JJR,JJS
	// anypos anypos
	private String translatePTB(String pos) {
		if (pos.equals("adverb"))
			return "RB";
		if (pos.equals("verb"))
			return "VB";
		if (pos.equals("noun"))
			return "NN";
		if (pos.equals("adj"))
			return "JJ";
		return "anypos";
	}

	private WordPolarity lookup(Map<String, WordPolarity> map, String token) {
		if (map == null)
			return null;
		return map.get(token);
	}

	public WordPolarity polarity(String token, String pos) {
		Map<String, WordPolarity> anypos = posWordPol.get("anypos");
		String ltoken = token.toLowerCase();
		if (pos.length() < 2)
			return null;
		String basePos = pos.substring(0, 2);

		WordPolarity anylookup = lookup(anypos, ltoken);
		if (anylookup != null)
			return anylookup;

		Map<String, WordPolarity> posMap = posWordPol.get(basePos);
		return lookup(posMap, ltoken);
	}
}
